package com.enterpriseDigitalPlatform.controller.renshi.attendance;

import com.enterpriseDigitalPlatform.dto.PageRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class AttendanceDao {
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public AttendanceDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 新加上班记录
    // 修改上班记录为下班记录

    public PageRes<Attendance> getList(AttendanceDTO attendanceDTO) {
        ArrayList<String> keyArr = new ArrayList<String>();
        ArrayList<Object> valueArr = new ArrayList<Object>();
        if (attendanceDTO.getId() != null) {
            keyArr.add("id = ?");
            valueArr.add(attendanceDTO.getId());
        }
        if (attendanceDTO.getDeptid() != null) {
            keyArr.add("deptid = ?");
            valueArr.add(attendanceDTO.getDeptid());
        }
        if (attendanceDTO.getStaffId() != null) {
            keyArr.add("staffid = ?");
            valueArr.add(attendanceDTO.getStaffId());
        }
        if (attendanceDTO.getWorkDay() != null) {
            keyArr.add("workday = ?");
        }
        if (attendanceDTO.getWorkMonth() != null) {
            keyArr.add("workmonth = ?");
        }
        if (attendanceDTO.getWorkYear() != null) {
            keyArr.add("workyear = ?");
        }
        if (attendanceDTO.getWorkDayStart() != null && attendanceDTO.getWorkDayEnd() != null) {
            keyArr.add("workday between ? and ?");
            valueArr.add(attendanceDTO.getWorkDayStart());
            valueArr.add(attendanceDTO.getWorkDayEnd());
        }
        String sql = "select * from attendance ";
        String sqlCount = "select count(*) from attendance ";
        if (!keyArr.isEmpty()) {
            sql += " where " + String.join(" and ", keyArr);
            sqlCount += " where " + String.join(" and ", keyArr);
        }
        Long total = jdbcTemplate.queryForObject(sqlCount, Long.class, valueArr.toArray());
        if (attendanceDTO.getPage() != null && attendanceDTO.getPageSize() != null) {
            sql += " order by id desc limit ?,?";
            valueArr.add((attendanceDTO.getPage() - 1) * attendanceDTO.getPageSize());
            valueArr.add(attendanceDTO.getPageSize());
        }
        List<Attendance> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Attendance.class), valueArr.toArray());
        return new PageRes<>(attendanceDTO.getPage(), attendanceDTO.getPageSize(), total, list);
    }
}
